"""
框架生命周期钩子具体实现

提供常用的生命周期钩子实现类，如数据库连接管理、缓存初始化等。
"""

import asyncio
import logging
from typing import Dict, Any, Optional, List
from abc import ABC, abstractmethod

from .lifecycle import ILifecycleHook, LifecycleStage


logger = logging.getLogger(__name__)


class DatabaseLifecycleHook(ILifecycleHook):
    """数据库连接生命周期钩子"""
    
    def __init__(self, db_manager=None):
        self.db_manager = db_manager
        self.name = "database"
        self.priority = 100  # 高优先级，最先启动，最后关闭
    
    async def on_startup(self, context: Dict[str, Any]) -> None:
        """启动时初始化数据库连接"""
        try:
            if self.db_manager:
                await self.db_manager.connect()
                logger.info("数据库连接已建立")
                context["database_ready"] = True
            else:
                logger.warning("未配置数据库管理器")
        except Exception as e:
            logger.error(f"数据库连接失败: {e}")
            raise
    
    async def on_shutdown(self, context: Dict[str, Any]) -> None:
        """关闭时断开数据库连接"""
        try:
            if self.db_manager:
                await self.db_manager.disconnect()
                logger.info("数据库连接已断开")
                context["database_ready"] = False
        except Exception as e:
            logger.error(f"数据库断开失败: {e}")
    
    async def health_check(self) -> bool:
        """检查数据库连接健康状态"""
        if not self.db_manager:
            return False
        
        try:
            return await self.db_manager.is_connected()
        except Exception as e:
            logger.error(f"数据库健康检查失败: {e}")
            return False


class CacheLifecycleHook(ILifecycleHook):
    """缓存系统生命周期钩子"""
    
    def __init__(self, cache_manager=None):
        self.cache_manager = cache_manager
        self.name = "cache"
        self.priority = 90  # 次高优先级
    
    async def on_startup(self, context: Dict[str, Any]) -> None:
        """启动时初始化缓存连接"""
        try:
            if self.cache_manager:
                await self.cache_manager.connect()
                logger.info("缓存系统已连接")
                context["cache_ready"] = True
            else:
                logger.info("未配置缓存管理器，跳过缓存初始化")
                context["cache_ready"] = False
        except Exception as e:
            logger.error(f"缓存连接失败: {e}")
            # 缓存失败不应该阻止应用启动
            context["cache_ready"] = False
    
    async def on_shutdown(self, context: Dict[str, Any]) -> None:
        """关闭时断开缓存连接"""
        try:
            if self.cache_manager:
                await self.cache_manager.disconnect()
                logger.info("缓存连接已断开")
                context["cache_ready"] = False
        except Exception as e:
            logger.error(f"缓存断开失败: {e}")
    
    async def health_check(self) -> bool:
        """检查缓存连接健康状态"""
        if not self.cache_manager:
            return True  # 没有缓存时认为是健康的
        
        try:
            return await self.cache_manager.ping()
        except Exception as e:
            logger.error(f"缓存健康检查失败: {e}")
            return False


class LoggingLifecycleHook(ILifecycleHook):
    """日志系统生命周期钩子"""
    
    def __init__(self, logging_config: Optional[Dict[str, Any]] = None):
        self.logging_config = logging_config or {}
        self.name = "logging"
        self.priority = 200  # 最高优先级，最先初始化
    
    async def on_startup(self, context: Dict[str, Any]) -> None:
        """启动时配置日志系统"""
        try:
            # 配置日志格式和处理器
            if self.logging_config:
                logging.config.dictConfig(self.logging_config)
            
            logger.info("日志系统已初始化")
            context["logging_ready"] = True
        except Exception as e:
            print(f"日志系统初始化失败: {e}")  # 使用print因为logger可能还未配置
            raise
    
    async def on_shutdown(self, context: Dict[str, Any]) -> None:
        """关闭时刷新日志缓冲区"""
        try:
            # 刷新所有日志处理器
            for handler in logging.root.handlers:
                if hasattr(handler, 'flush'):
                    handler.flush()
            
            logger.info("日志系统已关闭")
            context["logging_ready"] = False
        except Exception as e:
            print(f"日志系统关闭失败: {e}")
    
    async def health_check(self) -> bool:
        """检查日志系统健康状态"""
        try:
            # 简单的日志测试
            test_logger = logging.getLogger("health_check")
            test_logger.debug("日志系统健康检查")
            return True
        except Exception:
            return False


class EventBusLifecycleHook(ILifecycleHook):
    """事件总线生命周期钩子"""
    
    def __init__(self, event_bus=None):
        self.event_bus = event_bus
        self.name = "event_bus"
        self.priority = 80
    
    async def on_startup(self, context: Dict[str, Any]) -> None:
        """启动时初始化事件总线"""
        try:
            if self.event_bus:
                await self.event_bus.start()
                logger.info("事件总线已启动")
                context["event_bus_ready"] = True
            else:
                logger.info("未配置事件总线")
                context["event_bus_ready"] = False
        except Exception as e:
            logger.error(f"事件总线启动失败: {e}")
            raise
    
    async def on_shutdown(self, context: Dict[str, Any]) -> None:
        """关闭时停止事件总线"""
        try:
            if self.event_bus:
                await self.event_bus.stop()
                logger.info("事件总线已停止")
                context["event_bus_ready"] = False
        except Exception as e:
            logger.error(f"事件总线停止失败: {e}")
    
    async def health_check(self) -> bool:
        """检查事件总线健康状态"""
        if not self.event_bus:
            return True
        
        try:
            return self.event_bus.is_running()
        except Exception as e:
            logger.error(f"事件总线健康检查失败: {e}")
            return False


class MonitoringLifecycleHook(ILifecycleHook):
    """监控系统生命周期钩子"""
    
    def __init__(self, metrics_collector=None):
        self.metrics_collector = metrics_collector
        self.name = "monitoring"
        self.priority = 70
    
    async def on_startup(self, context: Dict[str, Any]) -> None:
        """启动时初始化监控系统"""
        try:
            if self.metrics_collector:
                await self.metrics_collector.start()
                logger.info("监控系统已启动")
                context["monitoring_ready"] = True
            else:
                logger.info("未配置监控系统")
                context["monitoring_ready"] = False
        except Exception as e:
            logger.error(f"监控系统启动失败: {e}")
            # 监控失败不应该阻止应用启动
            context["monitoring_ready"] = False
    
    async def on_shutdown(self, context: Dict[str, Any]) -> None:
        """关闭时停止监控系统"""
        try:
            if self.metrics_collector:
                await self.metrics_collector.stop()
                logger.info("监控系统已停止")
                context["monitoring_ready"] = False
        except Exception as e:
            logger.error(f"监控系统停止失败: {e}")
    
    async def health_check(self) -> bool:
        """检查监控系统健康状态"""
        if not self.metrics_collector:
            return True
        
        try:
            return self.metrics_collector.is_running()
        except Exception as e:
            logger.error(f"监控系统健康检查失败: {e}")
            return False


class CustomLifecycleHook(ILifecycleHook):
    """自定义生命周期钩子基类"""
    
    def __init__(self, name: str, priority: int = 50):
        self.name = name
        self.priority = priority
        self._startup_callbacks: List[callable] = []
        self._shutdown_callbacks: List[callable] = []
        self._health_callbacks: List[callable] = []
    
    def add_startup_callback(self, callback: callable) -> None:
        """添加启动回调"""
        self._startup_callbacks.append(callback)
    
    def add_shutdown_callback(self, callback: callable) -> None:
        """添加关闭回调"""
        self._shutdown_callbacks.append(callback)
    
    def add_health_callback(self, callback: callable) -> None:
        """添加健康检查回调"""
        self._health_callbacks.append(callback)
    
    async def on_startup(self, context: Dict[str, Any]) -> None:
        """执行所有启动回调"""
        for callback in self._startup_callbacks:
            try:
                if asyncio.iscoroutinefunction(callback):
                    await callback(context)
                else:
                    callback(context)
            except Exception as e:
                logger.error(f"启动回调失败 {callback}: {e}")
                raise
    
    async def on_shutdown(self, context: Dict[str, Any]) -> None:
        """执行所有关闭回调"""
        for callback in reversed(self._shutdown_callbacks):  # 反向执行
            try:
                if asyncio.iscoroutinefunction(callback):
                    await callback(context)
                else:
                    callback(context)
            except Exception as e:
                logger.error(f"关闭回调失败 {callback}: {e}")
    
    async def health_check(self) -> bool:
        """执行所有健康检查回调"""
        for callback in self._health_callbacks:
            try:
                if asyncio.iscoroutinefunction(callback):
                    result = await callback()
                else:
                    result = callback()
                
                if not result:
                    return False
            except Exception as e:
                logger.error(f"健康检查回调失败 {callback}: {e}")
                return False
        
        return True


# 钩子工厂函数
def create_database_hook(db_manager=None) -> DatabaseLifecycleHook:
    """创建数据库生命周期钩子"""
    return DatabaseLifecycleHook(db_manager)


def create_cache_hook(cache_manager=None) -> CacheLifecycleHook:
    """创建缓存生命周期钩子"""
    return CacheLifecycleHook(cache_manager)


def create_logging_hook(config: Optional[Dict[str, Any]] = None) -> LoggingLifecycleHook:
    """创建日志生命周期钩子"""
    return LoggingLifecycleHook(config)


def create_event_bus_hook(event_bus=None) -> EventBusLifecycleHook:
    """创建事件总线生命周期钩子"""
    return EventBusLifecycleHook(event_bus)


def create_monitoring_hook(metrics_collector=None) -> MonitoringLifecycleHook:
    """创建监控生命周期钩子"""
    return MonitoringLifecycleHook(metrics_collector)


def create_custom_hook(name: str, priority: int = 50) -> CustomLifecycleHook:
    """创建自定义生命周期钩子"""
    return CustomLifecycleHook(name, priority)
